package com.qifan.energy.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qifan.energy.base.BaseActivity;
import com.qifan.energy.bean.result.CartListResult;
import com.qifan.energy.bean.vo.CartItemVO;
import com.qifan.energy.mvp.callback.IEventBuyCallback;
import com.qifan.energy.mvp.callback.IEventOptionCallback;
import com.qifan.energy.mvp.callback.ISuccessCallBack;
import com.qifan.energy.R;
import com.qifan.energy.adapter.DetailImageAdapter;
import com.qifan.energy.adapter.ImageNetAdapter2;
import com.qifan.energy.bean.result.GoodsDetailResult;
import com.qifan.energy.bean.result.MemberInfo;
import com.qifan.energy.global.Constant;
import com.qifan.energy.global.Keys;
import com.qifan.energy.http.net.NetUtils;
import com.qifan.energy.http.response.MyObserver;
import com.qifan.energy.util.CheckUtil;
import com.qifan.energy.util.IntentUtils;
import com.qifan.energy.util.SharedPreferencesUtil;
import com.qifan.energy.util.ToastUtils;
import com.qifan.energy.util.UIUtils;
import com.qifan.energy.util.UMShareUtils;
import com.qifan.energy.util.eventbus.EventBusUtils;
import com.qifan.energy.util.eventbus.EventCode;
import com.qifan.energy.util.eventbus.EventMessage;
import com.qifan.energy.widget.dialog.AddCartBottomDialog;
import com.qifan.energy.widget.dialog.BuyBottomDialog;
import com.qifan.energy.widget.dialog.PaySuccessDialog;
import com.qifan.energy.widget.dialog.ShareBottomDialog;
import com.orhanobut.logger.Logger;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

public class GoodsDetailActivity extends BaseActivity {

    private GoodsDetailResult detailResult = new GoodsDetailResult();
    @BindView(R.id.detail_banner)
    Banner detailBanner;
    @BindView(R.id.price_tv)
    TextView priceTv;
    @BindView(R.id.original_price_tv)
    TextView originalPriceTv;
    @BindView(R.id.subtitle_tv)
    TextView subtitleTv;
    @BindView(R.id.product_name_tv)
    TextView productNameTv;
    @BindView(R.id.percent_tv)
    TextView percentTv;
    @BindView(R.id.spec_value_tv)
    TextView specValueTv;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    DetailImageAdapter imageAdapter;

    /*@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);
    }*/

    @Override
    protected int getLayoutId() {
        return R.layout.activity_goods_detail;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        /* 更改状态栏 */
        changeStatusTransparentFontBlack();
        //注册监听事件
        EventBusUtils.register(this);

        //初始化UI
        originalPriceTv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//中间
    }

    @Override
    protected void initData() {
        int goodsId = getIntent().getIntExtra(Keys.DETAIL_ID_KEY, -1);
        if (goodsId != -1){
            NetUtils.productDetail(String.valueOf(goodsId), new MyObserver<GoodsDetailResult>(this) {

                @Override
                public void onSuccess(GoodsDetailResult result) {
                    detailResult = result;
                    /* UI赋值 */
                    setUpUIWithResult(result);
                }

                @Override
                public void onFailure(Throwable e, String errorMsg) {
                    ToastUtils.showShort(errorMsg);
                }
            });
        }
    }

    /* 解析并且匹配 */
    private List<String> parseHtml(String html){
        List<String> imageList = new ArrayList<>();
        String reg = "http://.+?\\.(gif|jpeg|png|jpg|bmp)";
        Pattern pattern = Pattern.compile(reg);
        Matcher m = pattern.matcher(html);
        while (m.find()) {
            String imageUrl = m.group();
            imageList.add(imageUrl);
        }
        return imageList;
    }

    /* UI控件赋值 */
    private void setUpUIWithResult(GoodsDetailResult result){
        if (null != result){
            /* 设置Banner */
            if (CheckUtil.hasContent(result.getProduct().getAlbumPics())){
                String[] split = result.getProduct().getAlbumPics().split(",");
                List<String> albumPics = Arrays.asList(split);

                //设置banner
                if (detailBanner != null) {
                    detailBanner.setBackgroundResource(R.mipmap.icon_banner_default);
                    detailBanner.setIndicator(new CircleIndicator(this));
                    detailBanner.setIndicatorNormalColorRes(R.color.bg_gray);
                    detailBanner.setIndicatorSelectedColorRes(R.color.system_color);
                    detailBanner.setAdapter(new ImageNetAdapter2(albumPics));
                    /*detailBanner.setOnBannerListener((data, position) -> {
                        ToastUtils.showShort("请求首页数据测试");
                    });*/
                }
            }

            /* 设置其他信息 */
            priceTv.setText(String.format("%.02f",result.getProduct().getPrice()));
            subtitleTv.setText(result.getProduct().getSubTitle());
            productNameTv.setText(result.getProduct().getName());
            //percentTv.setText("50%");
            StringBuilder builder = new StringBuilder();
            if (CheckUtil.hasContent(result.getProductAttributeList())){
                for (GoodsDetailResult.ProductAttributeListBean bean : result.getProductAttributeList()){
                    builder.append("  ").append(bean.getName());
                }
                specValueTv.setText(builder.toString());
            }

            //详情底部图片
            List<String> imageUrls = parseHtml(result.getProduct().getDetailMobileHtml());
            if (CheckUtil.hasContent(imageUrls)) {
                imageAdapter = new DetailImageAdapter(imageUrls);
                recyclerView.setLayoutManager(new LinearLayoutManager(this));
                recyclerView.setAdapter(imageAdapter);
            }
        }
    }

    @OnClick(R.id.share_tv)
    void onShareTvClicked(){
        new ShareBottomDialog()
                .showNow2(getSupportFragmentManager(),"share")
                .setEventCallback(new IEventOptionCallback() {
            @Override
            public void onLeftConfirm() {
                shareWxLink();
            }

            @Override
            public void onRightConfirm() {
                shareWxLinkToCircle();
            }
        });
    }

    /* 分享朋友 */
    private void shareWxLink(){
        /* 获取本地用户信息 */
        MemberInfo result = SharedPreferencesUtil.getData(Keys.USER_INFO_MEMBER_KEY,new MemberInfo());
        if (!TextUtils.isEmpty(result.getInvitationCode())){
            UMShareUtils.shareWxLink(this, "吼吼~，一大波机会正向您走来"
                    ,String.format("抓住它不再犹豫，快来加入我们吧，邀请码：%s",result.getInvitationCode())
                    ,String.format(Constant.SHARE_GIFT + "?invitationCode=%s",result.getInvitationCode())
                    ,R.mipmap.ic_launcher, null);
        }
    }

    /* 分享朋友圈 */
    private void shareWxLinkToCircle(){
        /* 获取本地用户信息 */
        MemberInfo result = SharedPreferencesUtil.getData(Keys.USER_INFO_MEMBER_KEY,new MemberInfo());
        if (!TextUtils.isEmpty(result.getInvitationCode())){
            UMShareUtils.shareWxLinkToCircle(this, "吼吼~，一大波机会正向您走来"
                    ,String.format("抓住它不再犹豫，快来加入我们吧，邀请码：%s",result.getInvitationCode())
                    ,String.format(Constant.SHARE_GIFT + "?invitationCode=%s",result.getInvitationCode())
                    ,R.mipmap.ic_launcher, null);
        }
    }

    @OnClick(R.id.service_tv)
    void onServiceTvClicked(){
        IntentUtils.startActivity(this, MyServiceActivity.class);
    }


    @OnClick(R.id.add_cart_tv)
    void onaddCartTvClicked(){
        if (detailResult.getProduct() != null && !TextUtils.isEmpty(detailResult.getProduct().getPic())){
            new AddCartBottomDialog().showNow2(getSupportFragmentManager(),"addcart").setModel(detailResult).setEventCallback(new IEventBuyCallback() {
                @Override
                public void onCancel() {
                    /*ToastUtils.showShort("取消");*/
                }

                @Override
                public void onComfirm(CartItemVO cartItemVO) {
                    cartAdd(cartItemVO);
                }
            });
        }
    }

    /* 添加购物车接口 */
    private void cartAdd(CartItemVO cartItemVO){
        if (null != detailResult){
            cartItemVO.setProductSkuId(cartItemVO.getProductSkuId());
            cartItemVO.setProductSkuCode(cartItemVO.getProductSkuCode());
            NetUtils.cartAdd(cartItemVO, new MyObserver<Integer>(this) {
                @Override
                public void onSuccess(Integer result) {
                    EventBusUtils.post(new EventMessage<>(EventCode.EVENT_1, "EventData"));
                    ToastUtils.showShort("已加入购物车！");
                }

                @Override
                public void onFailure(Throwable e, String errorMsg) {
                    ToastUtils.showShort(errorMsg);
                }
            });
        }
    }

    @OnClick(R.id.spec_select_ll)
    void onSpecSelectLlClicked(){
        ToastUtils.showShort("选择规格！！！");
    }

    @OnClick(R.id.pay_tv)
    void onPayTvClicked(){
        if (detailResult.getProduct() != null && !TextUtils.isEmpty(detailResult.getProduct().getPic())){
            new BuyBottomDialog().showNow2(getSupportFragmentManager(),"buy").setModel(detailResult).setEventCallback(new IEventBuyCallback() {
                @Override
                public void onCancel() {
                    //ToastUtils.showShort("取消");
                }

                @Override
                public void onComfirm(CartItemVO cartItemVO) {
                    addCartAndBuyNow(cartItemVO);
                }
            });
        }
    }

    // 加入购物车
    private void addCartAndBuyNow(final CartItemVO cartItemVO){
        NetUtils.orderBuyNow(cartItemVO, new MyObserver<CartListResult>(this) {

            @Override
            public void onSuccess(CartListResult result) {
                Logger.i("加入购物车成功：" + result.getId());

                Intent intent = new Intent();
                intent.putExtra(Keys.CART_ORDER_TYPE,(Serializable)new ArrayList<CartListResult>(){{add(result);}});
                IntentUtils.startActivity(GoodsDetailActivity.this,ConfirmOrderActivity.class,intent);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    /**
     * 接收到分发的事件
     * @param event 事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventMessage event) {
        switch (event.getKey()) {
            case Keys.NOTIFY_EVENT.PAYSUCCESS:
                if (detailResult.getProduct() != null && detailResult.getProduct().getGiftTimeCard()>0 && detailResult.getProduct().getGiftGamePoint()>0 && detailResult.getProduct().getGiftCouponAmount()>0) {
                    UIUtils.getHandler().postDelayed(()->{
                        new PaySuccessDialog().showNow2(getSupportFragmentManager(),"paysuccess")
                                .setGoodsDetailResult(detailResult)
                                .setEventCallback(new ISuccessCallBack() {
                                    @Override
                                    public void onSuccess() {
                                        Logger.i("点击确定");
                                    }
                                });
                    },1000);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        //注销EventBus
        EventBusUtils.unregister(this);
        super.onDestroy();
    }
}
